var app = getApp();

function storetelephoneUserSigToLocalStorage(telephone, userSig) {
  // store the telephone, userSigto local storage
  wx.setStorage({
    key: "telephone",
    data: telephone
  });

  wx.setStorage({
    key: "userSig",
    data: userSig
  });
}
// end storetelephoneUserSigToLocalStorage

// 通过js_code发送request获取session_key和openid
function getSessionkeyAndOpenId() {
  // 请求官方接口，获取openid和session_key
  wx.request({
    url: "https://api.weixin.qq.com/sns/jscode2session",
    data: {
      appid: app.globalData.appid,
      secret: app.globalData.AppSecret,
      js_code: app.globalData.js_code,
      grant_type: "authorization_code"
    },
    success: function(res) {
      console.log("wx.request execute successfully!")
      app.globalData.openid = res.data.openid;
      app.globalData.session_key = res.data.session_key;
      console.log("the session key is " + app.globalData.session_key);
    },
    fail: function() {

    }
  })
  // 结束wx.request
}

function getjs_code() {
  wx.login({
    success: function(res) {
      if (res.code) {
        console.log("login success");
        console.log("get the js_code successfully,it's value is " + res.code);
        app.globalData.js_code = res.code;
        console.log("that.globalData.js_code is " + app.globalData.js_code);
        getSessionkeyAndOpenId();
      } else {
        console.log('获取用户登录态失败！' + res.errMsg)
      }
    }
  });
}
//end 

function isRegistered(){
  var telephone = wx.getStorageSync("telephone");
  console.log("telephone is " + telephone);
  var userSig = "";
  userSig = wx.getStorageSync("userSig");
  console.log("userSig is " + userSig)
  if (telephone.length > 0 && userSig.length > 0){
    return true;
  }else{
    return false;
  }
}
//end isRegistered
module.exports = {
  storetelephoneUserSigToLocalStorage: storetelephoneUserSigToLocalStorage,
  getSessionkeyAndOpenId: getSessionkeyAndOpenId,
  getjs_code: getjs_code,
  isRegistered: isRegistered
}